<!DOCTYPE html>
<html lang="en">
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>小吃详情</title>
    <link rel="shortcut icon" href="../static/favicon.ico" />
    <link rel="bookmark" href="/favicon.ico" />
    <link rel="stylesheet" type="text/css" href="../static/css/base.css">
    <link rel="stylesheet" type="text/css" href="../static/css/detail.css">
    <script type="text/javascript" src="../static/js/jquery-3.3.1.min.js"></script>
    <script type="text/javascript" src="../static/js/base.js"></script>
    <script type="text/javascript" src="../static/js/jquery.raty.min.js"></script>
    <script type="text/javascript" src="../static/js/jquery.dataTables.min.js"></script>
</head>

<body>
    <header>
        <div class="container clearfix" id="top">
            <a href="/index"><img class="logo" src="../static/img/logo.png"></a>
            <a class="topbar-item active" href="/index">首页</a>
            <a class="topbar-item " href="/category">小吃分类</a>
            <span th:if="${session.user} != null">
            <a class="topbar-item" href="/my" th:if="${session.user.username!='admin'}">个人中心</a>
            <a class="topbar-item" href="/admin" th:if="${session.user.username=='admin'}">个人中心</a>
            </span>
            <nav th:if="${session.user} == null">
                <a href="/register">注册</a>
                <span>|</span>
                <a href="/login">登录</a>
            </nav>
            <nav th:if="${session.user} != null">
                您好！<span id="username" th:text="${session.user.getUsername()}"></span>，<a href="/loginOut">退出</a>
            </nav>
        </div>
    </header>
    <a id="toTop"  title="回到顶部"><img src="../static/img/scroll_top1.png"></a>
    <div class="main-box">
        <div class="nav clearfix">
            <div class="fl clearfix nav-des">
                <img th:src="${food.getFoodImg()}" class="fl">
                <div class="fl nav-des-text">
                    <h2 class="ellipsis" th:text="${food.getName()}" th:title="${food.getName()}"></h2>
                    <div class="head clearfix">
                        <strong class="fl" th:if="${food.getScore()} eq '0'" th:text="暂无评分"></strong>
                        <strong class="fl" th:if="${food.getScore()} ne '0'" th:text="${food.getScore()}+'分'"></strong>
                        <span class="star-ranking fl">
                          <span id="totalScore" class="star-score" th:attr="data-score=${food.getScore()}"></span>
                        </span>
                    </div>
                </div>
            </div>
            <div class="nav-mid" >
                <p th:text="${food.intro}"></p>
            </div>
            <div class="fr clearfix nav-right">
                <div class="fl nav-right-collect">
                    <div id="like" th:class="${like}==1? 'not-collect collect':'not-collect'"  title="收藏餐厅"></div>
                    <div id="review-text" th:text="${like}==1? '已收藏':'未收藏'"></div>
                </div>
                <div class="category" th:text="${food.getCategory()}">
                </div>
            </div>
        </div>
        <div class="food-list">
            
               
            <div class="comments">
                <div class="title clearfix">
                    <div class="clearfix filters">
                        <label class="fl"><input name="category" type="radio" value="all" checked="checked"><span>全部评价</span></label>
                        <label class="fl"><input name="category" type="radio" value="good"><span>好评</span></label>
                        <label class="fl"><input name="category" type="radio" value="normal"><span>中评</span></label>
                        <label class="fl"><input name="category" type="radio" value="bad"><span>差评</span></label>
                    </div>
                </div>
                <div class="comments-list">
                    <table id="commentsTable">
                        <thead>
                            <tr>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                            </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </table>
                </div>
            </div>
        </div> 
        <div class="w-comment fr">
          <div class="title">我要写评论</div>
          <div class="w-comment_body">
              <div>打分：</div><div id="star"></div><span id="hint"></span>
              <div>评论：</div><div class="w-comment_text"><textarea maxlength="300"></textarea><span id="comment_count">0</span>/300</div>
              <button class="comment-submit">提交</button>
          </div>
        </div>   
    </div>

    <script  th:inline="javascript">
        var BaseUrl = '[(${BaseUrl})]';
        /*<![CDATA[*/
    $(function() {
        sessionStorage.setItem("tabLiNum",0);
        var table;
        commentsTable()
        $.fn.raty.defaults.path = '../static/img';
        $('#star').raty({
          target: '#hint',
          targetKeep: true
        });
        function timestampTodate(obj){
            var newDate = new Date();
            newDate.setTime(obj);
            return newDate.toLocaleString();
        }
        function  commentsTable() {
            table = $("#commentsTable").DataTable({
                destroy: true,
                "lengthChange": false,
                "processing": true,
                "deferRender": true,
                "pageLength": 5,
                "autoWidth":false,
                ajax: {
                    url: BaseUrl+"getAllComments?foodId="+GetQueryString("foodId"),
                },
                columns: [
                    { data: 'createTime',render:function (data,type,full,meta) {
                            var newtime = timestampTodate(data)
                            return "<span class='date fr'>"+newtime+"</span>"
                        } },
                    { data: 'score',render:function (data,type,full,meta) {
                            return "<div class='rank clearfix fr'> <span class='star-ranking fl'> <span class='star-score' style='width: "+data/5*72+"px'></span> </span> </div>"
                        } },
                    { data: 'comment',render:function (data,type,full,meta) {
                            return "<div class='comment-detail'>"+data+"</div>"
                        } },
                    { data:'user',render:function (data,type,full,meta) {
                            return "<img src='"+data.img+"' class='user_avatar'>";
                        }},
                    { data:'username',render:function (data,type,full,meta) {
                            return "<span class='user_phone fl'>"+data+"</span>";
                        }},
                    { data:'score',render:function (data,type,full,meta) {
                            return data;
                        }}
                ],
                "language": {
                    "zeroRecords": "没有找到记录",
                    "info": "第 _PAGE_ 页 ( 总共 _PAGES_ 页 )",
                    "infoEmpty": "无记录",
                    "infoFiltered": "(从 _MAX_ 条记录过滤)",
                    "paginate": {
                        "previous": "上一页",
                        "next": "下一页"
                    }
                },
            });
            table.order([0,'dsc']).draw();
        }
        $.fn.dataTable.ext.search.push(
            function( settings, data, dataIndex ) {
                var category= $(".filters input:checked").val();
                var score =  data[5] ; // use data for the age column
                if (category=="all"){
                    return true;
                }else if(category=="good"&&score>3){
                    return true;
                }else if(category=="normal"&&score==3){
                    return true;
                }else if(category=="bad"&&score<3){
                    return true;
                }
                return false;
            }
        );

        $(":radio").click(function () {
            table.order([0,'dsc']).draw();
        })

        $("#totalScore").width(function(){
            var score=$(this).attr("data-score");
            return score/5*150;
        })

        function GetQueryString(name)
        {
            var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if(r!=null)return  unescape(r[2]); return null;
        }
        $('#like').click(function() {
            if([[${session.user}]]==null){
                alert("请先登录！")
            }else{
                var username=$("#username").text();
                $(this).toggleClass('collect');
                var like_text = $('#review-text');
                console.log(data);
                if (like_text.text() == '未收藏') {
                    var data={
                        "username":username,
                        "foodid":GetQueryString("foodId")
                    }
                    like_text.text('已收藏');
                    $.ajax({
                        url:"/insertFavorite",
                        data:data,
                        type: 'POST',
                        cache: false,
                        success:function (data) {
                            if(data=="success"){
                                alert("收藏成功")
                            }
                        },
                        error:function () {
                            alert("操作失败！")
                        }
                    })
                } else {
                    var data={
                        "username":username,
                        "foodid":GetQueryString("foodId")
                    }
                    like_text.text('未收藏');
                    $.ajax({
                        url:"/deleteFavorite",
                        data:data,
                        type: 'POST',
                        cache: false,
                        success:function (data) {
                            if(data=="success"){
                                alert("取消收藏")
                            }
                        },
                        error:function () {
                            alert("操作失败！")
                        }
                    })
                }
            }
        })

        $("textarea").on("input",function(){
            $("#comment_count")[0].innerHTML=$(this).val().length
        })


        $(".comment-submit").click(function(){
            if([[${session.user}]]==null){
                alert("请先登录！")
            }else {
                var score = $("#star input").val();
                var comment = $(".w-comment_text textarea").val();
                if (score == "" || comment == "") {
                    alert("请输入内容！")
                } else {
                    var data={
                        "username":$("#username").text(),
                        "score":score,
                        "comment":comment,
                        "foodid":GetQueryString("foodId")
                    }
                    $.ajax({
                        url:"/insertComment",
                        data:data,
                        type: 'POST',
                        cache: false,
                        success:function (data) {
                            if(data=="success"){
                                alert("评论成功！")
                                window.location.reload();
                                $('#star').raty({
                                    target: '#hint',
                                    targetKeep: true
                                });
                                $(".w-comment_text textarea").val("");
                            }
                        },
                        error:function () {
                            alert("评论失败！")
                        }
                    })
                }
            }
        })
   
    })
        /*<![CDATA[*/
    </script>
</body>

</html>